<template>
  <el-dialog
    v-el-drag-dialog
    v-if="showDialog"
    :top="top + 'vh'"
    :modal="modal"
    :title="dialogTitle"
    :visible.sync="showDialog"
    :close-on-click-modal="closeOnClickModal"
    :width="width + '%'"
    :before-close="handleClose"
    append-to-body
  >
    <slot/>
    <el-row v-if="showButtons">
      <div class="dailog-footer">
        <span slot="footer" class="dialog-footer">
          <el-button v-if="showCancel" @click.native="close">取 消</el-button>
          <el-button
            v-if="showReset" @click.native="reset" type="warning"
          >{{resetButtonText}}</el-button
          >
          <el-button
            v-if="showConfirm"
            @click.native="debouncedSaveField(false)"
            type="success"
          >{{ confirmButtonText }}</el-button
          >
        </span>
      </div>
    </el-row>
  </el-dialog>
</template>
<script>
import elDragDialog from '@/directive/el-drag-dialog'
import {debounce} from 'throttle-debounce'

export default {
  name: 'DetailDialog',
  directives: {elDragDialog},
  props: {
    title: String,
    showButtons: {type: Boolean, default: true},
    show: {
      type: Boolean,
      default: false
    },
    modal: {
      type: Boolean,
      default: false
    },
    top: {
      type: Number,
      default: 15
    },
    width: {
      type: [String, Number],
      default: 50
    },
    showConfirm: {
      type: Boolean,
      default: true
    },
    showCancel: {
      type: Boolean,
      default: true
    },
    showReset: {
      type: Boolean,
      default: false
    },
    resetButtonText: {
      type: String,
      default: '重 置'
    },
    confirmButtonText: {
      type: String,
      default: '保 存'
    },
    closeOnClickModal: {type: Boolean, default: true}
  },
  data () {
    return {
      showDialog: this.show,
      dialogTitle: this.title,
      isAutoClose: false
    }
  },
  watch: {
    show (nVal, oVal) {
      this.showDialog = nVal
    },
    title (nVal, oVal) {
      this.dialogTitle = nVal
    }
  },
  created () {
    this.debouncedSaveField = debounce(300, this.save)
  },
  methods: {
    open (title, isAutoClose) {
      if (title) {
        this.dialogTitle = title
      }
      this.isAutoClose = isAutoClose
      this.showDialog = true
    },
    handleClose (done) {
      this.close()
      done()
    },
    save () {
      this.$emit('save')
    },
    reset () {
      this.$emit('reset')
    },
    close () {
      if (this.isAutoClose) {
        this.showDialog = false
      }
      this.$emit('update:show', false)
      this.$emit('close')
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
